#include "app_mqtt.h"
#include "log.h"
#include "MQTTClient.h"

static MQTTClient client;

static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; // MQTT客户端连接选项

static MQTTClient_message pubmsg = MQTTClient_message_initializer;                  // MQTT客户端要发布的消息

static int (*receivecallback)(char *data,int len);

static void app_mqtt_connectionLost(void* context, char* cause){
    MQTTClient_destroy(client);
    log_error("连接丢失, 原因：%s", cause);
}

//1是成功 0是失败
static int app_mqtt_messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* message){
    char *data = message->payload;
    int len = message->payloadlen;
    log_info("数据为%s,长度为%d",data,len);
    int ret=0;
    if (receivecallback)
    {
        ret = receivecallback(data,len) == 0?1:0;   
    }
     // 释放消息
     MQTTClient_freeMessage(&message);
     MQTTClient_free(topicName);
     
    return ret;
}

static void app_mqtt_deliveryComplete(void* context, MQTTClient_deliveryToken dt){
    log_debug("消息已成功发送");
}

/**
 * @brief 初始化mqtt
 */
void app_mqtt_init(){
    //初始化mqtt客户端
    int ret = MQTTClient_create(&client,server_uri,uuid,MQTTCLIENT_PERSISTENCE_NONE,NULL);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        log_error("create_error");
        return;
    }
    
    //设置回调函数
    ret = MQTTClient_setCallbacks(client,NULL,app_mqtt_connectionLost,app_mqtt_messageArrived,app_mqtt_deliveryComplete);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        log_error("create_error");
        return;
    }
    //mqtt连接
    ret = MQTTClient_connect(client,&conn_opts);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        log_error("create_error");
        return;
    }
    //订阅话题
    ret = MQTTClient_subscribe(client,mqtt_pull,mqtt_qos);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        log_error("create_error");
        return;
    }
}

/**
 * @brief 发送消息
 * @param 要发送的数据
 * @param 发送数据的长度
 */

int app_mqtt_send(char *data,int datalen){
    pubmsg.payload = data;
    pubmsg.payloadlen = datalen;
    pubmsg.qos = mqtt_qos;
    int ret = MQTTClient_publishMessage(client,mqtt_push,&pubmsg,NULL);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        log_error("create_error");
        return -1;
    }
    return 0;
}

/**
 * @brief 接收消息回调函数
 */
int app_mqtt_receivecallback(int (*callback)(char *data,int len)){
    receivecallback = callback;
    return 0;
}

/**
 * @brief 销毁函数
 */
void app_mqtt_destroy(){
    MQTTClient_disconnect(client,10000);
    MQTTClient_destroy(client);
}
